package com.mall.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.mall.auth.feign.SystemFeignService;
import com.mall.auth.service.AuthService;
import com.mall.common.LoginMallUser;
import com.mall.common.constants.JwtConstants;
import com.mall.common.constants.TokenConstants;
import com.mall.common.domain.MallUser;
import com.mall.common.domain.response.JwtResponse;
import com.mall.common.result.Result;
import com.mall.common.utils.JwtUtils;
import com.mall.common.utils.TelSmsUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wangy
 * @version 1.0
 * @description: TODO
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private SystemFeignService systemFeignService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     *
     * @param loginMallUser 参数
     * @return JwtResponse
     */
    @Override
    public JwtResponse login(LoginMallUser loginMallUser) {
        Result<MallUser> mallUserResult = systemFeignService.findUserByPhone(loginMallUser.getPhone());
        MallUser mallUser = mallUserResult.getData();
        //验证手机号
        if (mallUser == null) {
            throw new RuntimeException("手机号不存在");
        }
        //验证验证码
        String code = redisTemplate.opsForValue().get(loginMallUser.getPhone());
        if (code == null){
            throw new RuntimeException("验证码未发送");
        }
        if (!code.equals(loginMallUser.getCode())) {
            throw new RuntimeException("验证码不正确");
        }
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY, userKey);
        String token = JwtUtils.createToken(map);
        //用户信息保存到redis当中，JWT过期时间为20分钟
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey, JSON.toJSONString(mallUser), 20, TimeUnit.MINUTES);
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTimeStr("20MIN");
        return jwtResponse;
    }

    /**
     * 发送验证码
     *
     * @param phone 参数
     */
    @Override
    public void sendCode(String phone) {
        String str = redisTemplate.opsForValue().get(phone);
        // 实现短信防刷功能
        if (str != null) {
            throw new RuntimeException("验证码已发送请稍后再试!!!");
        }
        //生成随机数
        String code = RandomUtil.randomNumbers(4);
        HashMap<String, String> map = new HashMap<>();
        map.put(phone, code);
        //发送验证码
        TelSmsUtils.sendSms(phone, code, map);
        //验证码以手机号保存到redis当中
        redisTemplate.opsForValue().set(phone, code, 10, TimeUnit.MINUTES);
    }
    /**
     * 获取用户信息
     *
     * @return MallUser
     */
    @Override
    public MallUser info() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJson = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSON.parseObject(userJson, MallUser.class);
    }
    /**
     * 注销
     */
    @Override
    public void logout() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
